package com.weng.sso.sdk.http;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.weng.framework.core.model.ResponseData;
import com.weng.sso.core.config.SsoConfig;
import com.weng.sso.core.model.AuthReq;
import okhttp3.*;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


public class HttpClient {


    private String serverUrl;

    private String appId;

    private String appSecret;



    /**
     * 请求超时时间（秒）
     */
    private long requestTimeout = 60 * 1000;

    private static OkHttpClient okHttpClient = null;

    public HttpClient(String appId, String appSecret,  long requestTimeout) {
        this.appId = appId;
        this.appSecret = appSecret;
        this.requestTimeout = requestTimeout;

        // 初始化http客户端
        if (ObjectUtil.isNull(okHttpClient)) {
            okHttpClient = new OkHttpClient.Builder()
                    .connectTimeout(requestTimeout, TimeUnit.MILLISECONDS)
                    .readTimeout(requestTimeout, TimeUnit.MILLISECONDS)
                    .writeTimeout(requestTimeout, TimeUnit.MILLISECONDS)
                    .build();
        }
    }

    /**
     * 设置请求头
     *
     * @param builder
     * @return
     */
    private Request.Builder setHeader(Request.Builder builder) {
        String timestamp = DateUtil.currentSeconds() + "";
        builder.addHeader(SsoConfig.HEADER_APP_ID, this.appId)
                .addHeader(SsoConfig.HEADER_TIMESTAMP, timestamp)
                .addHeader(SsoConfig.HEADER_SIGN, this.makeSign(timestamp));
        return builder;
    }

    /**
     * 生成签名
     *
     * @param timestamp
     * @return
     */
    private String makeSign(String timestamp) {
        StringBuffer buf = new StringBuffer();
        buf.append(this.appId);
        buf.append(this.appSecret);
        buf.append(timestamp);
        return SecureUtil.md5(buf.toString());
    }

    /**
     * Post请求
     *
     * @param reqData
     * @param url
     * @return
     */
    public   ResponseData  post(String url, AuthReq reqData) {
        try {

            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
            RequestBody body = RequestBody.create(mediaType, JSONObject.toJSONString(reqData));

            Request.Builder builder = new Request.Builder().url(url).post(body);
            builder = this.setHeader(builder);
            Request request = builder.build();

            Response response = okHttpClient.newCall(request).execute();
            String res = response.body().string();
            return JSONObject.parseObject(res,  new TypeReference<ResponseData>() {});

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseData.failed(e.getMessage());
        }
    }



    /**
     * Get请求
     *
     * @param url
     * @return
     */
    public  ResponseData get(String url) {
        try {
            Request.Builder builder = new Request.Builder().url(url).get();
            builder = this.setHeader(builder);
            Request request = builder.build();

            Response response = okHttpClient.newCall(request).execute();
            String res = response.body().string();
            return JSONObject.parseObject(res, new TypeReference<ResponseData>() {});
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseData.failed(e.getMessage());
        }
    }


}